package com.bjfu.gmms.servlet;

import com.bjfu.gmms.MyBatisUtil;
import com.bjfu.gmms.mapper.RetestTableMapper;
import com.bjfu.gmms.mapper.RetestTableMapper2;
import com.bjfu.gmms.mapper.StudentInfoMapper;
import com.bjfu.gmms.model.RetestTable;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/processAdmission")
public class ProcessAdmissionServlet extends HttpServlet {
    private RetestTableMapper2 retestTableMapper;
    private StudentInfoMapper studentInfoMapper; // add 用来查询学科名称
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String studentId = request.getParameter("studentId");
        // String passCode = request.getParameter("passCode");
        String passCodeByName = request.getParameter("passCodeByName");


        SqlSession sqlSession = MyBatisUtil.getSqlSession("development");
        retestTableMapper = sqlSession.getMapper(RetestTableMapper2.class);
        // 改：根据学科名称查询学科 ID（字符串类型）
        studentInfoMapper = sqlSession.getMapper(StudentInfoMapper.class);
        String passCode = studentInfoMapper.getDisciplineIdByName(passCodeByName);
        System.out.println(passCodeByName);
        if (passCode == null) {
            throw new ServletException("无法找到对应的学科ID");
        }

        try {
            RetestTable retestTable = new RetestTable();
            retestTable.setStudentId(Integer.parseInt(studentId));
            retestTable.setPassCode(passCode);

            retestTableMapper.updateRetestPasscode(retestTable);
            sqlSession.commit();
            // 录取成功后跳转到 adminSecretaryDashboard.jsp
            response.sendRedirect("adminSecretaryDashboard.jsp");
        } catch (Exception e) {
            // 出现异常时跳转回同一页面，并携带错误信息
            request.setAttribute("errorMessage", "录取失败，请重试");
            request.getRequestDispatcher("confirmAdmission.jsp").forward(request, response);
        }
    }
}


